const modulesSort = {
  namespaced: true,
  state: {
    sorts: []
  },

  mutations: {
    initSorts: (state, arr) => {
      state.sorts = arr
    },
    addSorts: (state, { id, sort }) => {
      state.sorts.push({ id, sort })
    },
    updateSorts: (state, { id, sort }) => {
      state.sorts.forEach((item) => {
        if (item.id === id) item.sort = sort
      })
    },
    deleteSort: (state, id) => {
      const res = state.sorts.filter((item) => {
        return item.id !== id
      })
      state.sorts = res
    }
  },

  actions: {
    isExistence({ commit, state }, { id, sort, callbackFun }) {
      if (!state.sorts.length) {
        commit('addSorts', { id, sort })
        return
      }
      const existSort = state.sorts.some((item) => item.sort === sort)
      const existId = state.sorts.some((item) => item.id === id)
      if (existSort) {
        let flag = false
        state.sorts.forEach((item) => {
          if (item.sort === sort) flag = item.id === id
        })
        if (flag) commit('updateSorts', { id, sort })
        else callbackFun()
        return
      }
      if (!existSort && existId) commit('updateSorts', { id, sort })
      else if (!existSort && !existId) commit('addSorts', { id, sort })
    }
  }
}
export default modulesSort
